package com.zmzncs.lmtc.module.customer.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmzncs.lmtc.common.util.WeChatUtil;
import com.zmzncs.lmtc.common.pojo.AuthorizeVO;
import com.zmzncs.lmtc.common.pojo.LoginUser;
import com.zmzncs.lmtc.common.util.*;
import com.zmzncs.lmtc.module.customer.dao.*;
import com.zmzncs.lmtc.module.customer.pojo.car.CarDTO;
import com.zmzncs.lmtc.module.customer.pojo.card.CardDTO;
import com.zmzncs.lmtc.module.customer.pojo.cardmonthrecord.CardMonthRecordDTO;
import com.zmzncs.lmtc.module.customer.pojo.customer.*;
import com.zmzncs.lmtc.module.customer.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 客户-客户信息 服务实现类
 * </p>
 *
 * @author 任建波
 * @since 2020-08-26
 */
@Service
@Slf4j
public class CustomerServiceImpl extends ServiceImpl<CustomerDao, Customer> implements CustomerService {

    @Autowired
    CustomerDao customerDao;
    @Autowired
    CarDao carDao;
    @Autowired
    CardDao cardDao;
    @Autowired
    CardMonthRecordDao cardMonthRecordDao;
    @Autowired
    CardParkDao cardParkDao;

    @Autowired
    HttpServletRequest request;

    /**
     * 微信授权
     */
    @Override
    @Transactional
    public AuthorizeVO authorize(CustomerForm customerForm) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WeChatUtil.xcxAppId + "&secret=" + WeChatUtil.xcxAppSecret + "&js_code=" + customerForm.getCode() + "&grant_type=authorization_code";
        String response = HttpUtil.requestGet(url, null, null);
        JSONObject jsonObject = JSONObject.parseObject(response);
        if(jsonObject.get("openid") == null){
            ExceptionUtil.businessException("openid为空");
        }
        if(jsonObject.get("session_key") == null){
            ExceptionUtil.businessException("session_key空");
        }

        //  获取openid
        String openid = jsonObject.get("openid").toString();
        //  获取session_key
        String sessionKey = jsonObject.get("session_key").toString();

        //  根据openid查询客户
        CustomerDTO customerDTO = customerDao.getCustomerByOpenId(openid);

        Customer customer = new Customer();
        customer.setOpenid(openid); //  openid
        customer.setSessionKey(sessionKey); // session_key
        if(jsonObject.get("unionid") != null){
            customer.setUnionid(jsonObject.get("unionid").toString()); // unionid
        }
        customer.setAvatar(customerForm.getAvatar());   //  头像
        customer.setNickname(customerForm.getNickname());   //  昵称
        customer.setSex(customerForm.getSex().getCode());   //  性别
        //  第一次使用，添加
        if (customerDTO == null) {
            customerDao.insert(customer);
        } else {
            //  已经使用，修改
            customer.setId(customerDTO.getId());
            customerDao.updateById(customer);
        }

        LoginUser loginUser = new LoginUser();
        loginUser.setCustomerId(customer.getId());
        loginUser.setNickname(customer.getNickname());
        loginUser.setOpenid(customer.getOpenid());
        loginUser.setUnionid(customer.getUnionid());
        String token = JwtUtil.createJWT(loginUser);

        AuthorizeVO authorizeVO = new AuthorizeVO();
        authorizeVO.setToken(token);
        authorizeVO.setCustomerId(customer.getId());
        return authorizeVO;
    }

    /**
     * 会员详情
     */
    @Override
    public CustomerDTO getCustomerInfo() {
        LoginUser loginUser = JwtUtil.getLoginUser(request);
        CustomerDTO customerDTO = customerDao.getCustomerById(loginUser.getCustomerId());
        CardDTO cardDTO = cardDao.getBalance(loginUser.getCustomerId());
        customerDTO.setBalance(cardDTO == null ? new BigDecimal(0) : cardDTO.getCardBalance());

        return customerDTO;
    }

    //  获取客户月租服务
    @Override
    public List<CardDTO> getCustomerMonthCardList(){
        LoginUser loginUser = JwtUtil.getLoginUser(request);

        //  立码停车月租
        List<CardDTO> customerMonthCardList = cardDao.getCustomerMonthCardList(loginUser.getCustomerId());
        for(CardDTO cardDTO: customerMonthCardList){
            int daysLeft = DateTimeUtil.betweenDays(cardDTO.getExpireTime(), new Date());
            cardDTO.setDaysLeft(daysLeft);    //  当天算一天，所有加一
        }

        return customerMonthCardList;
    }

    //  获取客户时长服务
    @Override
    public List<CardDTO> getCustomerDurationCard(){
        LoginUser loginUser = JwtUtil.getLoginUser(request);

        //  获取客户时长服务
        List<CardDTO> customerDurationCardList = cardDao.getCustomerDurationCardList(loginUser.getCustomerId());

        //  获取客户车辆
        List<CarDTO> customerCarList = carDao.getCustomerCarList(loginUser.getCustomerId());
        List<String> carNumberList = customerCarList.stream().map(CarDTO::getCarNumber).collect(Collectors.toList());

        if (customerDurationCardList != null && !customerDurationCardList.isEmpty()){
            for(CardDTO cardDTO: customerDurationCardList){
                cardDTO.setCarNumberList(carNumberList);
            }
        }

        return customerDurationCardList;
    }

    //  获取客户余额
    @Override
    public CardDTO getRechargeCard(){
        LoginUser loginUser = JwtUtil.getLoginUser(request);
        //  获取客户时长服务
        CardDTO getRechargeCard = cardDao.getBalance(loginUser.getCustomerId());
        return getRechargeCard;
    }


    /**
     * 客户授权绑定手机号
     */
    @Transactional
    public String bindMobilePhone(String code, String encryptedData, String iv) {
        LoginUser loginUser = JwtUtil.getLoginUser(request);

        JSONObject jsonObject = WeChatUtil.getPhoneNumber(encryptedData, code, iv);
        if (jsonObject != null && jsonObject.size() != 0) {
            String phoneNumber = jsonObject.getString("phoneNumber");
            Customer customer = new Customer();
            customer.setId(loginUser.getCustomerId());
            customer.setMobilePhone(phoneNumber);
            customerDao.updateById(customer);
            return phoneNumber;
        } else {
            ExceptionUtil.businessException("获取手机号出错，请重试");
        }
        return null;
    }

    @Override
    public String transfersToUser(String orderCode,String openid, BigDecimal totalFee, String desc) {

        Map<String, Object> map = WeChatUtil.transfers(orderCode, openid, totalFee, desc);
        if (map != null && "SUCCESS".equals(map.get("resultCode"))){
            return "向用户付款成功";
        } else {
            return "向用户付款失败";
        }
    }


}
